package com.jayqqaa12.admin.controller;

import com.jayqqaa12.admin.model.Res;
import com.jayqqaa12.admin.model.Role;
import com.jayqqaa12.jbase.jfinal.ext.ctrl.JsonController;
import com.jayqqaa12.model.json.SendJson;
import com.jayqqaa12.shiro.ShiroCache;
import com.jayqqaa12.shiro.ShiroInterceptor;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.spring.Inject;

@ControllerBind(controllerKey = "/admin/res")
public class ResController extends JsonController<Res> {

	@Inject.BY_TYPE
	Res resDao;
	@Inject.BY_TYPE
	Role roleDao;

	public void tree() throws Exception {

		Integer pid = getParaToInt("id");
		Integer passId = getParaToInt("passId");
		int type = getParaToInt("type", Res.TYPE_MEUE);
		renderJson(resDao.getTree(pid, type, passId));
	}

	public void list() {
		Integer pid = getParaToInt("id");
		SendJson json = getJsonObject();

		if (pid != null) json.setData("parent", resDao.findById(pid));
		json.setData("list", resDao.list(pid));
		
		sendJson(json);
	}

	public void delete() {
		renderJsonResult(resDao.deleteByIdAndPid(getParaToInt("id")));
		removeAuthorization();
	}
	
	public void batchDelete(){

		renderJsonResult(resDao.batchDelete(getPara("ids")));
	}

	public void save() {
		Res res = getModel();

		boolean result = false;

		if (res.getId() == null) {
			result = res.save();
			roleDao.grant(1, res.getId() + "");
		} else result = res.update();

		removeAuthorization();

		renderJsonResult(result);
	}

	private void removeAuthorization() {
		ShiroCache.clearAuthorizationInfoAll();
		ShiroInterceptor.updateUrls();
	}

}
